package com.my.lucky.service;

import com.my.lucky.model.Filter;
import com.my.lucky.repository.FilterRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class FilterService {

    private final FilterRepository filterRepository;

    @Autowired
    public FilterService(FilterRepository filterRepository) {
        this.filterRepository = filterRepository;
    }

    /**
     * 获取所有保存的过滤条件
     */
    public List<Filter> getAllFilters() {
        return filterRepository.findAll();
    }

    /**
     * 根据ID获取过滤条件
     */
    public Optional<Filter> getFilterById(Long id) {
        return filterRepository.findById(id);
    }

    /**
     * 保存新的过滤条件
     */
    public Filter saveFilter(Filter filter) {
        // 设置创建时间
        filter.setCreatedAt(LocalDateTime.now());
        return filterRepository.save(filter);
    }

    /**
     * 更新过滤条件
     */
    public Filter updateFilter(Long id, Filter filterDetails) {
        return filterRepository.findById(id)
                .map(filter -> {
                    filter.setName(filterDetails.getName());
                    filter.setDescription(filterDetails.getDescription());
                    filter.setConditions(filterDetails.getConditions());
                    return filterRepository.save(filter);
                })
                .orElseThrow(() -> new RuntimeException("Filter not found with id " + id));
    }

    /**
     * 删除过滤条件
     */
    public void deleteFilter(Long id) {
        filterRepository.deleteById(id);
    }
}
